// ==UserScript==
// @name         纳米AI聊天文字显示优化
// @namespace    http://tampermonkey.net/
// @version      1.2
// @description  优化纳米AI聊天界面的文字显示效果，包括文本大小和行高控制，聊天区域宽度优化，缩小顶部banner，底部输入框自动隐藏
// @author       You
// @match        https://bot.n.cn/chat*
// @run-at       document-end
// @grant        GM_addStyle
// ==/UserScript==

(function() {
    'use strict';
    
    // 直接添加必要的样式
    GM_addStyle(`
        /* 面板样式 */
        #text-control-panel {
            position: fixed;
            top: 20px;
            right: 20px;
            background-color: rgba(255, 255, 255, 0.9);
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
            z-index: 10000;
            width: 250px;
            transition: opacity 0.3s;
            border: 1px solid #ccc;
        }
        
        /* 小圆点样式 */
        #panel-toggle {
            position: fixed;
            top: 20px;
            right: 20px;
            width: 35px;
            height: 35px;
            border-radius: 50%;
            background-color: #1E90FF;
            cursor: pointer;
            z-index: 10001;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 18px;
            border: 2px solid white;
        }
        
        /* 滑块样式 */
        .slider-container {
            margin-bottom: 15px;
        }
        
        .slider-container label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #333;
        }
        
        .slider-container input[type="range"] {
            width: 100%;
            height: 8px;
        }
        
        /* 优化聊天宽度 */
        .sm\\:max-w-776px {
            max-width: 100% !important;
            width: 100% !important;
        }
        
        .message-list-container {
            width: 100% !important;
            max-width: 100% !important;
            padding-left: 20px !important;
            padding-right: 20px !important;
        }
        
        .message-item-content {
            width: 100% !important;
            max-width: 100% !important;
        }
        
        .w-55\\/100 {
            width: 100% !important;
        }
        
        #message-list {
            width: 100% !important;
        }
        
        /* 缩小顶部banner */
        #chat-header {
            transform: scale(0.7) !important;
            transform-origin: top left !important;
            height: 50px !important;
            min-height: 50px !important;
            overflow: hidden !important;
        }
        
        /* 调整上方间距，补偿banner高度缩小后的空间 */
        #message-list {
            padding-top: 0 !important;
            padding-bottom: 140px !important;
        }
        
        /* 底部输入框样式控制 */
        #NM-ASSISTANT_chat_input {
            transition: transform 0.3s ease, max-height 0.3s ease, opacity 0.3s ease !important;
            transform-origin: bottom center !important;
        }
        
        /* 底部输入框隐藏时的样式 */
        #NM-ASSISTANT_chat_input.hidden-input {
            transform: translateY(80%) !important;
            max-height: 50px !important;
            opacity: 0.6 !important;
            cursor: pointer !important;
        }
        
        /* 添加一个小提示箭头帮助用户定位 */
        #NM-ASSISTANT_chat_input.hidden-input::before {
            content: "↑";
            position: absolute;
            top: -15px;
            left: 50%;
            transform: translateX(-50%);
            background-color: rgba(0, 0, 0, 0.5);
            color: white;
            width: 25px;
            height: 25px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            opacity: 0.8;
            z-index: 10001;
        }
        
        /* 底部输入框悬停提示的样式 */
        #input-hover-tip {
            position: fixed;
            bottom: 10px;
            left: 50%;
            transform: translateX(-50%);
            padding: 5px 20px;
            background-color: rgba(0,0,0,0.5);
            color: white;
            border-radius: 20px;
            font-size: 14px;
            opacity: 0.8;
            transition: opacity 0.3s ease;
            z-index: 10002;
            pointer-events: none;
        }
        
        /* 底部协议文字样式调整 */
        .absolute.left-0.right-0.bottom-0.flex.w-full.justify-center.text-12px {
            transition: transform 0.3s ease, opacity 0.3s ease !important;
        }
        
        /* 底部协议文字隐藏时样式 */
        .absolute.left-0.right-0.bottom-0.flex.w-full.justify-center.text-12px.hidden-footer {
            transform: translateY(100%) !important;
            opacity: 0 !important;
        }
    `);

    // 主函数 - 使用setTimeout确保页面完全加载
    setTimeout(function() {
        console.log('纳米AI聊天文字优化脚本: 开始初始化');
        
        // 创建和添加控制面板
        createControlPanel();
        
        // 应用banner样式
        applyBannerStyle();
        
        // 设置底部输入框控制
        setupInputAreaControl();
        
        // 监听DOM变化
        observeDOM();
        
        // 定期检查面板是否存在
        setInterval(checkPanelExists, 3000);
        
        // 定期检查并应用banner样式
        setInterval(applyBannerStyle, 3000);
        
        // 定期检查底部输入框
        setInterval(checkInputAreaExists, 3000);
    }, 1500);
    
    // 创建控制面板
    function createControlPanel() {
        // 检查是否已存在
        removeExistingElements();
        
        // 创建面板
        const panel = document.createElement('div');
        panel.id = 'text-control-panel';
        panel.innerHTML = `
            <div class="slider-container">
                <label>文本大小: <span id="font-size-value">16</span>px</label>
                <input type="range" id="font-size-slider" min="5" max="45" value="16" step="2">
            </div>
            <div class="slider-container">
                <label>行高倍数: <span id="line-height-value">1.5</span></label>
                <input type="range" id="line-height-slider" min="0.5" max="5" value="1.5" step="0.2">
            </div>
            <div style="margin-top: 15px; display: flex; justify-content: space-between;">
                <button id="reset-button" style="background: #ff5252; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-weight: bold;">恢复默认</button>
                <button id="toggle-input-button" style="background: #4caf50; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-weight: bold;">显示/隐藏输入框</button>
            </div>
        `;
        
        // 创建小圆点
        const dot = document.createElement('div');
        dot.id = 'panel-toggle';
        dot.textContent = 'A';
        dot.style.display = 'none'; // 初始隐藏圆点
        
        // 添加到body
        document.body.appendChild(panel);
        document.body.appendChild(dot);
        
        console.log('纳米AI聊天文字优化脚本: 控制面板已创建');
        
        // 添加事件监听
        setupEventListeners();
        
        // 应用保存的设置
        applySavedSettings();
        
        // 定时隐藏面板
        setTimeout(() => {
            hidePanel();
        }, 8000);
    }
    
    // 移除可能已存在的控制元素
    function removeExistingElements() {
        const existingPanel = document.getElementById('text-control-panel');
        const existingDot = document.getElementById('panel-toggle');
        
        if (existingPanel) existingPanel.remove();
        if (existingDot) existingDot.remove();
    }
    
    // 设置事件监听器
    function setupEventListeners() {
        const panel = document.getElementById('text-control-panel');
        const dot = document.getElementById('panel-toggle');
        const fontSizeSlider = document.getElementById('font-size-slider');
        const lineHeightSlider = document.getElementById('line-height-slider');
        
        // 检查元素是否存在
        if (!panel || !dot || !fontSizeSlider || !lineHeightSlider) {
            console.error('纳米AI聊天文字优化脚本: 控制元素未找到');
            return;
        }
        
        // 滑块事件
        fontSizeSlider.addEventListener('input', handleFontSizeChange);
        lineHeightSlider.addEventListener('input', handleLineHeightChange);
        
        // 面板和圆点事件
        panel.addEventListener('mouseenter', function() {
            clearTimeout(window.panelTimeout);
        });
        
        panel.addEventListener('mouseleave', function() {
            window.panelTimeout = setTimeout(hidePanel, 5000);
        });
        
        // 添加鼠标悬浮到小圆点上的事件
        dot.addEventListener('mouseenter', showPanel);
        // 保留原有的点击事件
        dot.addEventListener('click', showPanel);
        
        // 添加恢复默认和切换输入框按钮事件
        const resetButton = document.getElementById('reset-button');
        const toggleInputButton = document.getElementById('toggle-input-button');
        
        if (resetButton) {
            resetButton.addEventListener('click', resetAllSettings);
        }
        
        if (toggleInputButton) {
            toggleInputButton.addEventListener('click', toggleInputArea);
        }
    }
    
    // 字体大小变化处理
    function handleFontSizeChange() {
        const value = this.value;
        document.getElementById('font-size-value').textContent = value;
        applyStyles();
    }
    
    // 行高变化处理
    function handleLineHeightChange() {
        const value = this.value;
        document.getElementById('line-height-value').textContent = value;
        applyStyles();
    }
    
    // 显示面板
    function showPanel() {
        const panel = document.getElementById('text-control-panel');
        const dot = document.getElementById('panel-toggle');
        
        if (panel && dot) {
            panel.style.display = 'block';
            dot.style.display = 'none';
            
            clearTimeout(window.panelTimeout);
            window.panelTimeout = setTimeout(hidePanel, 8000);
        }
    }
    
    // 隐藏面板
    function hidePanel() {
        const panel = document.getElementById('text-control-panel');
        const dot = document.getElementById('panel-toggle');
        
        if (panel && dot) {
            panel.style.display = 'none';
            dot.style.display = 'flex';
        }
    }
    
    // 应用保存的设置
    function applySavedSettings() {
        const savedFontSize = localStorage.getItem('namiAI-fontSize') || 16;
        const savedLineHeight = localStorage.getItem('namiAI-lineHeight') || 1.5;
        
        const fontSizeSlider = document.getElementById('font-size-slider');
        const lineHeightSlider = document.getElementById('line-height-slider');
        const fontSizeValue = document.getElementById('font-size-value');
        const lineHeightValue = document.getElementById('line-height-value');
        
        if (fontSizeSlider && lineHeightSlider) {
            fontSizeSlider.value = savedFontSize;
            lineHeightSlider.value = savedLineHeight;
            
            if (fontSizeValue) fontSizeValue.textContent = savedFontSize;
            if (lineHeightValue) lineHeightValue.textContent = savedLineHeight;
            
            applyStyles();
        }
    }
    
    // 应用文本样式
    function applyStyles() {
        const fontSizeSlider = document.getElementById('font-size-slider');
        const lineHeightSlider = document.getElementById('line-height-slider');
        
        if (!fontSizeSlider || !lineHeightSlider) return;
        
        const fontSize = fontSizeSlider.value;
        const lineHeight = lineHeightSlider.value;
        
        // 保存设置
        localStorage.setItem('namiAI-fontSize', fontSize);
        localStorage.setItem('namiAI-lineHeight', lineHeight);
        
        // 应用样式
        const styleId = 'nami-text-style';
        let styleElem = document.getElementById(styleId);
        
        if (!styleElem) {
            styleElem = document.createElement('style');
            styleElem.id = styleId;
            document.head.appendChild(styleElem);
        }
        
        styleElem.textContent = `
            .markdown-container, 
            .markdown-container p,
            .markdown-container li,
            .markdown-container code,
            .markdown-container table,
            .markdown-container td,
            .markdown-container th,
            .markdown-container tr,
            .markdown__table-container table,
            .markdown__table-container td,
            .markdown__table-container th,
            .markdown__table-container tr,
            table, 
            td, 
            th,
            tr,
            tbody,
            thead,
            .message-item-content,
            .message-item-content table,
            .message-item-content td,
            .message-item-content th,
            .whitespace-pre-line,
            .whitespace-pre-wrap,
            .ds-content,
            .ds-content table,
            .ds-content td,
            .ds-content th,
            .message-item-content > div > p,
            pre code {
                font-size: ${fontSize}px !important;
                line-height: ${lineHeight} !important;
                /* 不要加背景和颜色，保持原样 */
                position: relative;
                z-index: 1;
            }
            
            /* 表格特殊处理 */
            .markdown-container table td,
            .markdown-container table th,
            .markdown__table-container table td,
            .markdown__table-container table th,
            table td,
            table th {
                padding: 8px !important;
                font-size: ${fontSize}px !important;
                border-width: 1px !important;
            }
            
            /* 移除 body 和 #nworld-app-container 的黑色背景，不再设置 */
        `;

        // 移除 body 和 #nworld-app-container 的黑色背景
        document.body.style.background = '';
        document.body.style.backgroundImage = '';
        const appContainer = document.getElementById('nworld-app-container');
        if (appContainer) {
            appContainer.style.background = '';
            appContainer.style.backgroundImage = '';
        }

        // 将带有格子背景的元素放到底层并变透明
        document.querySelectorAll('[style*="background"]').forEach(el => {
            const bg = el.style.background || el.getAttribute('style');
            if (bg && (bg.includes('url(') || bg.includes('linear-gradient'))) {
                el.style.setProperty('background', 'transparent', 'important');
                el.style.setProperty('background-image', 'none', 'important');
                el.style.setProperty('position', 'relative', 'important');
                el.style.setProperty('z-index', '0', 'important');
            }
        });

        // 只保留最底层黑色背景层
        if (!document.getElementById('nami-black-bg')) {
            const blackBg = document.createElement('div');
            blackBg.id = 'nami-black-bg';
            blackBg.style.position = 'fixed';
            blackBg.style.left = '0';
            blackBg.style.top = '0';
            blackBg.style.width = '100vw';
            blackBg.style.height = '100vh';
            blackBg.style.background = '#000';
            blackBg.style.zIndex = '0';
            blackBg.style.pointerEvents = 'none';
            document.body.prepend(blackBg);
        }

        console.log(`纳米AI聊天文字优化脚本: 应用样式 - 字体大小: ${fontSize}px, 行高: ${lineHeight}，已强制黑色背景`);
    }
    
    // 监听DOM变化
    function observeDOM() {
        const observer = new MutationObserver(function(mutations) {
            applyStyles();
        });
        
        observer.observe(document.body, {
            childList: true,
            subtree: true,
            attributes: false,
            characterData: false
        });
    }
    
    // 检查控制面板是否存在
    function checkPanelExists() {
        const panel = document.getElementById('text-control-panel');
        const dot = document.getElementById('panel-toggle');
        
        if (!panel || !dot || !document.body.contains(panel) || !document.body.contains(dot)) {
            console.log('纳米AI聊天文字优化脚本: 控制面板丢失，重新创建');
            createControlPanel();
        }
    }
    
    // 应用banner样式
    function applyBannerStyle() {
        const header = document.getElementById('chat-header');
        if (!header) return;
        
        // 应用样式
        header.style.transform = 'scale(0.7)';
        header.style.transformOrigin = 'top left';
        header.style.height = '50px';
        header.style.minHeight = '50px';
        header.style.overflow = 'hidden';
        
        // 修改内部元素大小
        const elements = header.querySelectorAll('*');
        elements.forEach(el => {
            // 检查元素是否有className属性且不为空
            if (!el.className || typeof el.className !== 'string' || !el.className.trim()) {
                return;
            }
            
            // 获取原始类中的尺寸数值
            const classNames = el.className.split(' ');
            
            // 处理大小相关的类
            for (let i = 0; i < classNames.length; i++) {
                const cls = classNames[i];
                
                // 跳过空类名
                if (!cls || cls.trim() === '') continue;
                
                // 尺寸和间距处理
                if (cls.includes('size-') || cls.includes('px') || 
                    cls.includes('h-') || cls.includes('w-') ||
                    cls.includes('min-w-') || cls.includes('gap-') || 
                    cls.includes('mr-') || cls.includes('ml-') || 
                    cls.includes('mt-') || cls.includes('mb-') ||
                    cls.includes('p-') || cls.includes('px-') || 
                    cls.includes('py-') || cls.includes('pt-') || 
                    cls.includes('pb-') || cls.includes('pl-') || 
                    cls.includes('pr-')) {
                    
                    // 不替换有特殊标记的类
                    if (cls.includes('!')) continue;
                    
                    const match = cls.match(/(\d+)/);
                    if (match) {
                        const value = parseInt(match[1]);
                        const newValue = Math.round(value * 0.7);
                        if (newValue > 0) {
                            try {
                                const newCls = cls.replace(match[1], newValue.toString());
                                el.classList.remove(cls);
                                el.classList.add(newCls);
                            } catch (error) {
                                console.error('处理类名时出错:', error, cls);
                            }
                        }
                    }
                }
                
                // 字体大小处理
                if (cls.includes('text-') && cls.match(/\d+/)) {
                    const match = cls.match(/(\d+)/);
                    if (match) {
                        const value = parseInt(match[1]);
                        const newValue = Math.round(value * 0.7);
                        if (newValue > 0) {
                            try {
                                const newCls = cls.replace(match[1], newValue.toString());
                                el.classList.remove(cls);
                                el.classList.add(newCls);
                            } catch (error) {
                                console.error('处理文本大小类名时出错:', error, cls);
                            }
                        }
                    }
                }
            }
        });
        
        console.log('纳米AI聊天文字优化脚本: Banner样式已应用');
    }
    
    // 设置底部输入框控制
    function setupInputAreaControl() {
        const inputArea = document.getElementById('NM-ASSISTANT_chat_input');
        const footer = document.querySelector('.absolute.left-0.right-0.bottom-0.flex.w-full.justify-center.text-12px');
        
        if (!inputArea) {
            console.log('纳米AI聊天文字优化脚本: 未找到底部输入框区域');
            return;
        }
        
        // 创建悬停提示
        let hoverTip = document.getElementById('input-hover-tip');
        if (!hoverTip) {
            hoverTip = document.createElement('div');
            hoverTip.id = 'input-hover-tip';
            hoverTip.textContent = '鼠标移入显示输入框';
            hoverTip.style.opacity = '0';
            document.body.appendChild(hoverTip);
        }
        
        // 为输入区域添加类以便控制显示和隐藏
        inputArea.classList.add('hidden-input');
        if (footer) {
            footer.classList.add('hidden-footer');
        }
        
        // 显示提示
        setTimeout(() => {
            hoverTip.style.opacity = '0.8';
            
            // 提示显示3秒后消失
            setTimeout(() => {
                hoverTip.style.opacity = '0';
            }, 3000);
        }, 1000);
        
        // 添加鼠标事件
        inputArea.addEventListener('mouseenter', function() {
            showInputArea();
            
            // 提示消失
            hoverTip.style.opacity = '0';
        });
        
        inputArea.addEventListener('mouseleave', function() {
            // 检查是否有文本输入，如果有则不隐藏
            const textarea = inputArea.querySelector('textarea');
            if (textarea && textarea.value.trim() !== '') {
                return;
            }
            
            // 检查是否处于焦点状态，如果是则不隐藏
            const isTextareaFocused = document.activeElement === textarea;
            if (isTextareaFocused) {
                return;
            }
            
            // 延迟3秒隐藏
            window.inputAreaTimeout = setTimeout(hideInputArea, 3000);
        });
        
        // 监听文本输入事件
        const textarea = inputArea.querySelector('textarea');
        if (textarea) {
            textarea.addEventListener('focus', function() {
                // 文本框获取焦点时，取消隐藏计时器
                if (window.inputAreaTimeout) {
                    clearTimeout(window.inputAreaTimeout);
                    window.inputAreaTimeout = null;
                }
            });
            
            textarea.addEventListener('input', function() {
                // 输入内容时，取消隐藏计时器
                if (window.inputAreaTimeout) {
                    clearTimeout(window.inputAreaTimeout);
                    window.inputAreaTimeout = null;
                }
                
                // 如果有输入内容，确保输入区域显示
                if (this.value.trim() !== '') {
                    showInputArea();
                }
            });
        }
        
        // 给隐藏的输入框添加点击事件
        inputArea.addEventListener('click', function() {
            if (inputArea.classList.contains('hidden-input')) {
                showInputArea();
            }
        });
        
        // 初始化时隐藏输入区域
        hideInputArea();
    }
    
    // 显示输入区域
    function showInputArea() {
        const inputArea = document.getElementById('NM-ASSISTANT_chat_input');
        const footer = document.querySelector('.absolute.left-0.right-0.bottom-0.flex.w-full.justify-center.text-12px');
        
        if (inputArea) {
            inputArea.classList.remove('hidden-input');
            
            // 清除可能存在的隐藏定时器
            if (window.inputAreaTimeout) {
                clearTimeout(window.inputAreaTimeout);
                window.inputAreaTimeout = null;
            }
        }
        
        if (footer) {
            footer.classList.remove('hidden-footer');
        }
    }
    
    // 隐藏输入区域
    function hideInputArea() {
        const inputArea = document.getElementById('NM-ASSISTANT_chat_input');
        const footer = document.querySelector('.absolute.left-0.right-0.bottom-0.flex.w-full.justify-center.text-12px');
        
        if (inputArea) {
            inputArea.classList.add('hidden-input');
        }
        
        if (footer) {
            footer.classList.add('hidden-footer');
        }
    }
    
    // 检查底部输入框是否存在
    function checkInputAreaExists() {
        const inputArea = document.getElementById('NM-ASSISTANT_chat_input');
        
        // 如果输入区域不存在，尝试重新设置
        if (!inputArea) {
            console.log('纳米AI聊天文字优化脚本: 底部输入框不存在，重新设置');
            setupInputAreaControl();
        }
    }
    
    // 添加新函数：恢复默认设置
    function resetAllSettings() {
        // 恢复文本大小和行高默认值
        const fontSizeSlider = document.getElementById('font-size-slider');
        const lineHeightSlider = document.getElementById('line-height-slider');
        const fontSizeValue = document.getElementById('font-size-value');
        const lineHeightValue = document.getElementById('line-height-value');
        
        if (fontSizeSlider && lineHeightSlider) {
            fontSizeSlider.value = 16;
            lineHeightSlider.value = 1.5;
            
            if (fontSizeValue) fontSizeValue.textContent = 16;
            if (lineHeightValue) lineHeightValue.textContent = 1.5;
            
            // 保存默认设置
            localStorage.setItem('namiAI-fontSize', 16);
            localStorage.setItem('namiAI-lineHeight', 1.5);
        }
        
        // 恢复banner正常大小
        const header = document.getElementById('chat-header');
        if (header) {
            header.style.transform = '';
            header.style.transformOrigin = '';
            header.style.height = '';
            header.style.minHeight = '';
            header.style.overflow = '';
        }
        
        // 显示输入区域
        showInputArea();
        
        // 移除特殊样式
        const styleId = 'nami-text-style';
        let styleElem = document.getElementById(styleId);
        if (styleElem) {
            styleElem.textContent = '';
        }
        
        console.log('纳米AI聊天文字优化脚本: 已恢复默认设置');
    }
    
    // 添加新函数：切换输入框显示状态
    function toggleInputArea() {
        const inputArea = document.getElementById('NM-ASSISTANT_chat_input');
        if (!inputArea) return;
        
        if (inputArea.classList.contains('hidden-input')) {
            showInputArea();
        } else {
            hideInputArea();
        }
    }
})();
